package com.aggregate.pay.saobei.support.client;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.saobei.support.Client;
import com.aggregate.pay.saobei.support.Factory;
import com.aggregate.pay.saobei.support.Merch;
import com.aggregate.pay.saobei.support.utils.MD5;

/**
 * 扫呗支付接口-微信公众号JSAPI支付授权
 * @author Moyq5
 * @date 2018年7月10日
 */
public class AuthOpenId implements Client<String, String> {
	
	private static final Logger log = LoggerFactory.getLogger(AuthOpenId.class);
	
	private Merch merch;
	
	public AuthOpenId(Merch merch) {
		this.merch = merch;
	}

	@Override
	public String execute(String redirectUri) {
		// 按固定字段固定顺序组装签名
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("merchant_no", merch.merchantNo());
		map.put("redirect_uri", redirectUri);
		map.put("terminal_no", merch.terminalId());
		
		StringBuffer sb = new StringBuffer();
		String value;
		for (Entry<String, Object> entry: map.entrySet()) {
			value = null == entry.getValue() ? "": String.valueOf(entry.getValue());
			sb.append(entry.getKey() + "=" + value + "&");
		}
		sb.append("access_token=" + merch.accessToken());

		log.debug("签名内容：{}", sb.toString());
		String sign = MD5.MD5Encode(sb.toString());
		log.debug("签名值：{}", sign);
		
		try {
			map.put("redirect_uri", URLEncoder.encode(redirectUri, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		map.put("key_sign", sign);
		
		sb = new StringBuffer();
		for (Entry<String, Object> entry: map.entrySet()) {
			value = null == entry.getValue() ? "": String.valueOf(entry.getValue());
			sb.append(entry.getKey() + "=" + value + "&");
		}
		sb.delete(sb.length() - 1, sb.length());
		
		return getApiPath() + "?" + sb.toString();
	}
	
	private String getApiPath() {
		return Factory.getConfig().serverPath() + "/wx/jsapi/authopenid";
	}
	
}
